package com.mapforge.listener;

import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

/**
 * The {@link MapEditorKeyEventDispatcher} class listens to {@link KeyEvent key
 * events} occuring in the main application a global level. This class exists
 * because some components need to know whenever a key is pressed, regardless of
 * what component had focus when that key event occurred.
 * 
 * @see KeyEventDispatcher
 * @author Will Morrison
 * 
 */
public class MapEditorKeyEventDispatcher implements KeyEventDispatcher {
	private List<KeyListener> globalListeners;

	public MapEditorKeyEventDispatcher() {
		globalListeners = new ArrayList<KeyListener>();
		KeyboardFocusManager.getCurrentKeyboardFocusManager()
				.addKeyEventDispatcher(this);
	}

	public boolean addKeyEventOccurredListener(KeyListener listener) {
		return this.globalListeners.add(listener);
	}

	public boolean removeKeyEventOccurredListener(KeyListener listener) {
		return this.globalListeners.remove(listener);
	}

	public void clearKeyEventOccurredListeners() {
		globalListeners.clear();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent e) {
		Object obj = e.getSource();
		e.setSource(this);
		switch (e.getID()) {
		case KeyEvent.KEY_PRESSED:
			for (KeyListener listener : globalListeners) {
				listener.keyPressed(e);
			}
			break;
		case KeyEvent.KEY_RELEASED:
			for (KeyListener listener : globalListeners) {
				listener.keyReleased(e);
			}
			break;
		case KeyEvent.KEY_TYPED:
			for (KeyListener listener : globalListeners) {
				listener.keyTyped(e);
			}
			break;
		}
		e.setSource(obj);
		// return whether event is discarded, we'll never discard event
		return false;
	}
}
